<template>
<!-- 左右合并关系展示 -->
<div style="width:98%;height: calc(100% - 30px); background:white; overflow:auto">
  <div v-if="isShowEchartsDome" id="eleViewTree" style="width:150%; background:white; min-height:  calc(100% - 20px);">
  </div>
  <el-button v-if="!isShowEchartsDome" @click="showpup"  class="el-icon-circle-plus">添加关联关系</el-button>
</div>
</template>
<script>
import {ADDMERGE,QUERYELEVIEW} from '@api/url'
export default {
  data(){
    return{
      spanArr:[],
      myChart:null,
      eleviewsData:[],
      isShowEchartsDome:true,//默认展示
      pos:null,
      ListArow:[],
      slaveId:"",
      content:{},
       option:{
        axisExpandable:{
          rootToNode:true
        },
        containLabel:true,
          series:[
            {
                type: 'tree',
                collapsed:false,
                // path:"../../assets/image/make.png",
                symbol: "image://@images/make/delete.png",//影藏圆圈
                isExpand:true,
                symbolSize: 18,
                roam: "move",//如果只想要开启缩放或者平移，可以设置成 'scale' 或者 'move'。设置成 true 为都开启
                id: 0,
                name: 'tree1',
                data: [],
                labelLine: { // 设置指示线的长度
                  normal: {
                    length: 2,
                    length2: 2
                  }
                },
                // 渲染样式
                 itemStyle: {
                    borderWidth:0,
                    borderColor: '#c23531',
                    emphasis: {
                      shadowBlur: 10,
                      shadowOffsetX: 0,
                      shadowColor: 'blue',
                       
                    }
                  },
                top: '1%',//距离顶部高度
                left: '15%',//距离容器
                bottom: '10%',//距离底部距离
                right: '45%',//距离右边距离
                edgeForkPosition: '90%',//树占高度
                initialTreeDepth: 4,//展开层次

                lineStyle: {
                    width: 2 //线粗
                },

                label: {
                    backgroundColor: '#fff',//背景色
                    position: 'left',//定位
                    verticalAlign: 'bottom',//文字显示位置
                    align: 'right',
                    show:true,
                    fontSize:16//字体大小
                },

                leaves: {
                    label: {
                        position: 'right',
                        verticalAlign: 'bottom',
                        align: 'left'
                    }
                },

                emphasis: {
                    focus: 'self', //'none' 不淡出其它图形，默认使用该配置。'self' 只聚焦（不淡出）当前高亮的数据的图形。'series' 聚焦当前高亮的数据所在的系列的所有图形。
                    blurScope: 'descendant' //'coordinateSystem' 淡出范围为坐标系，默认使用该配置。'series' 淡出范围为系列。'global' 淡出范围为全局。
                },

                expandAndCollapse: true,
                animationDuration: 0,
                animationDurationUpdate: 0
            }
        ]
       }
    }
  },
  props:{
    showeleviewsData:{
      type:Object,
      default:null
    },
    menuData:{
      type:Object,
      default:null
    }
  },
  computed:{
  // 新增自助数据集信息
    addelevanceObj(){
      debugger
      return this.$storeSave.state.addelevanceObj
    }
  },
  watch:{
    showeleviewsData(val){
      this.queryElevanceViews(val)
    }
  },
  mounted(){
    // this.creatTree()
    console.log(this.showeleviewsData)
    //如果不是新增数据集合，就不用查询
    if (this.$storeSave.state.updateObj.menuId || this.$storeSave.state.addelevanceObj.menuId) {
      this.queryElevanceViews()
    }
    
  },
  methods:{
    showpup(){
      this.$emit('closePage','showpup')
    },
    doit(){
      console.log(this.content)
      this.detailData={}
      let makePath = `image://${require("../../assets/image/make.png")}`
      let delpath=`image://${require("../../assets/image/delete.png")}`
      if (this.content.length>0) {
        this.detailData.name=this.content[0].masterTableName//主表名称赋值
        this.detailData.symbol="none",
        this.detailData.tierId='1'//设置层级，便于确定点击事件判断 主表层
        this.detailData.children=[]//关联关系名称，取决于有几条关联数据 
        this.content.forEach(ele=>{
          this.detailData.children.push({
            name:this.getLabel(ele.relationMode),//赋值关联关系
            tierId:"2",//设置层级，便于确定点击事件判断 关联关系层
            symbolSize:18, 
            symbol:makePath,
            masterId: ele.masterId,
            masterTableName: ele.masterTableName,
            modelId: ele.modelId,
            optMode: ele.optMode,
            relationId: ele.relationId,
            relationMode: ele.relationMode,
            seqno: ele.seqno,
            showPost: ele.showPost,
            slaveId: ele.slaveId,
            slaveTableName: ele.slaveTableName,
            children:[{
              name:ele.slaveTableName,
              tierId:"3", //设置层级，便于确定点击事件判断 关联表民称层
              relationId:ele.relationId, //关联id
              modelId:ele.modelId, //模型id 
              symbolSize:18,
              symbol:delpath,
              slaveId: ele.slaveId,
              children:[]
              }]//存辅表名称
          })
          ele.lists.forEach(item=>{//把字段赋值到
            this.detailData.children.forEach(child=>{
              if (child.relationId==ele.relationId) {
                child.children[0].children.push({
                  tierId:"4", //设置层级，便于确定点击事件判断 字段层
                  name:`主表字段：${item.masterShowfld}——辅表字段：${item.slaveShowfld}`,
                  symbol:"none",
                  relationId:item.relationId,
                  modelId:item.modelId,
                  slaveId:item.slaveId,
                  relationMode:item.relationMode,
                  relationModeLabel:this.getLabel(item.relationMode),
                  slaveTableName:item.slaveTableName,
                  masterTableName:item.masterTableName,
                  masterId:item.masterId,
                  masterShowfld:item.masterShowfld,
                  slaveShowfld:item.slaveShowfld,
                  sFldType:item.sFldType,
                  mFldType:item.mFldType
                })
              }
            })
          })
        })
        this.option.series[0].data[0]=this.detailData
        console.log(this.option.series[0].data)
      }else{
        this.option.series[0].data[0]={name:"暂无数据"}
      }
      this.creatTree()
    },
    creatTree(){
      let chartDom = document.getElementById('eleViewTree');
      let myChart
      //防止出现“There is a chart instance already initialized on the dom.”的警告    
      //在使用echarts发现需要及时对新建的myChart实例进行销毁,否则会出现上述警告   
      chartDom = document.getElementById('eleViewTree');
      myChart = this.$echarts.init(chartDom); 
      if(!myChart) {
          myChart.clear()
      }
      chartDom = document.getElementById('eleViewTree');
      myChart = this.$echarts.init(chartDom); 
      setTimeout(myChart.setOption(this.option), 500);
      myChart.on('click', params=>{
        console.log('___________________')
        console.log(params.data.collapsed)
        if (params.componentType === 'series') {
          console.log(params)
            console.log("params.componentType === 'series'")
                // dataIndex  2 点击编辑 
                // data index 3 点击删除
                if (params.data.tierId=='2') {
                  this.modify(params.data.children[0].children)
                //  alert('点击了编辑按钮')
                }else if (params.data.tierId=='3') {
                  // alert('点击了删除按钮')
                  this.$confirm('此操作删除该记录, 是否继续?', '提示', '确认信息', {
                    distinguishCancelAndClose: true,
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    center: true
                  }).then(() => {
                      this.deleteData(params.data)
                    }).catch(action => {
                      // 以下两行代码为了实现点击子节点不伸缩
                      //防止出现“There is a chart instance already initialized on the dom.”的警告    
                      //在使用echarts发现需要及时对新建的myChart实例进行销毁,否则会出现上述警告    
                      if(!myChart) {
                          myChart.clear();
                      }
                      chartDom = document.getElementById('eleViewTree');
                      myChart = this.$echarts.init(chartDom);
                      setTimeout(myChart.setOption(this.option), 500);
                      console.log("取消删除")
                    });
                }
          
          }
      });
    },
  queryElevanceViews(data){
      console.log('查询关联关系')
    console.log(data)
    debugger
      this.$storeSave.state.activeTable=[]
      let queryId=""
      this.isShowEchartsDome=true
      if (data) {//关联成功查询
        queryId= data.modelId
      }else{
        //点击编辑进来的时候查询
        console.log('点击编辑进来的时候查询')
        queryId=this.$storeSave.state.updateObj.menuId ? this.$storeSave.state.updateObj.menuId : this.$storeSave.state.addelevanceObj.menuId
      }
      console.log(this.menuData.menuId,'this.menuData.menuId')
      console.log(this.addelevanceObj,'this.addelevanceObj')
      let param={
        //关联成功后表id 
        modelId:queryId
      }
      if (queryId) {
        this.$http.post(QUERYELEVIEW,param).then(res=>{
          console.log('查询关联视图信息成功')
          console.log(res)
          this.ListArow=[]
          let val=res.data.data;
          this.content=res.data.data
          if (res.data.code=='200' && res.data.data.length>0) {
            //1、将主表附表id收集起来，在可选表上显示可选字段
            let newArray=[];
            //2、给每条数据赋值
              res.data.data.forEach((item,index)=>{
                if (index==0) {
                  newArray.push(item.masterId)
                }else{
                  let have=newArray.indexOf(item.masterId)
                  if (have==-1) {
                    newArray.push(item.masterId)
                  }
                }
                item.lists.forEach(ele=>{
                ele.relationId=item.relationId;
                ele.modelId=item.modelId;
                ele.slaveId=item.slaveId;
                ele.relationMode=item.relationMode;
                ele.relationModeLabel=this.getLabel(item.relationMode)
                ele.slaveTableName=item.slaveTableName;
                ele.masterTableName=item.masterTableName
                ele.masterId=item.masterId
                this.ListArow.push(ele)
                  let have=newArray.indexOf(ele.slaveId)
                  if (have==-1) {
                    newArray.push(ele.slaveId)
                  }
              })
            })
            console.log('______________++++++++++++++++++++已选表有哪些')
            console.log(newArray)
            this.$storeSave.state.activeTable=newArray;
            this.slaveId=val.slaveId//连接表id
            this.$storeSave.state.mainTableData.menuId=this.ListArow[0].masterId//点关联按钮时给主表信息查询赋值，
            this.$storeSave.state.mainTableData.name=this.ListArow[0].masterTableName//主表名称
          }else{
            this.ListArow=[]
            this.isShowEchartsDome=false
          }
          this.doit()
          console.log('---------------------------------00000000000000000000000000000')
        }).catch(err=>{
          debugger
          this.isShowEchartsDome=false
          this.content={}
          this.doit()
        })
      }
    },
    getLabel(relationType){
          let arr=[{value:2,label:"左连接"},{value:3,label:"右连接"}]
          let label=""
          arr.forEach(ele=>{
            if (relationType==ele.value) {
              label=ele.label
            }
          })
         return label
        },
    //修改
    modify(data){
      console.log('需要修改的数据是：',data)
      this.$emit('tagisShowpup',data,{modelId:this.showeleviewsData.menuId,slaveId:this.slaveId})
    },
    //删除
    deleteData(data){
      console.log(data)
      debugger
      console.log('==============')
      let param={
         optMode:"D",
          modelId:data.modelId, //模型id 写死
          slaveId:data.slaveId,  //从表id
          relationId:data.relationId, //关联id
      }
      this.$http.post(ADDMERGE,param).then(res=>{
        console.log(res)
        if (res.data.code=="200") {
          this.isShowEchartsDome=false
          this.queryElevanceViews()//重新查询关联视图
          this.$confirm('删除成功', '提示', {
            confirmButtonText: '确定',
            type: 'success'
          })
          
          //显示预览
          // this.closePup()
          //删除dom节点

        }else{
          this.$confirm(res.data.message, '提示', {
            confirmButtonText: '确定',
            type: 'fail'
          })
        }
      }).catch(err=>{
        console.log(err)
        this.$confirm('删除失败', '提示', {
            confirmButtonText: '确定',
            type: 'fail'
          })
      })
    },
    
  }
  
}
</script>
<style lang="less" scoped>

</style>